import axios from 'axios'
import statusCodes from './statuscodes.js'
import router from '/src/router/index.js'
import { ElMessage } from 'element-plus'

axios.defaults.baseURL = 'http://localhost:6666'
axios.defaults.withCredentials = true
axios.defaults.timeout = 10000

const CancelToken = axios.CancelToken
let source = CancelToken.source()
// axios 请求拦截器
axios.interceptors.request.use(config => {
	// console.log(config)
    config.cancelToken = source.token
    return config
}, error => {
    console.log('请求拦截错误信息')
    console.dir(error)
})

// axios 响应拦截器
axios.interceptors.response.use(response => {
	return response
}, error => {
	return Promise.reject(error)
})


/**
 * 
 * @param {请求方法} method 
 * @param {请求地址} url 
 * @param {请求参数} parameter 
 * params: get等方法的参数, 
 * data: post等方法的参数
 * @param {额外选项} options 
 * isSign: 接口是否需要鉴权 
 * isHandleError: 是否处理错误
 * @returns
 */
const request = function (
    method,
    url,
    parameter = { 
        params: null, 
        data: null 
    }, 
    options = { 
        isSign: true, 
        isHandleError: true
    }
) {
	let headers = {}
	if (options.isSign) {
		headers['x-auth-token'] = 'xxxxxx'
		headers['lang'] = 'zh-CN'
	}
    return new Promise((resolve) => {
        axios({
            method,
            url,
            params: parameter.params,
            data: parameter.data,
            responseType: 'json',
            responseEncoding: 'utf8',
            xsrfCookieName: 'XSRF-TOKEN',
            xsrfHeaderName: 'X-XSRF-TOKEN',
			headers,
        }).then(response => {
			// console.log(response)
			if (response.status == 200 && response.data.code == 200) {
				resolve([response, null])
			} else {
				if (options.isHandleError) {
					let infoTipRes = statusCodes.infoTip.find(item => item.code == response.data.code)
					let offlineRes = statusCodes.offline.find(item => item.code == response.data.code)
					if (infoTipRes || offlineRes) {
						ElMessage({
							message: response.data.message,
							type: 'error',
							grouping: true,
						})
					}
					if (offlineRes) {
						// TODO 下线处理 并 中断后续的请求
					}
					resolve([null, null])
				}
				resolve([null, response])
			}
        }).catch(error => {
			console.log('响应错误信息')
			console.dir(error)
			let message = ''
			if (error.message.indexOf('timeout') !== -1) {
			    message = '请求超时'
			} else if (error.message == 'Network Error') {
				message = '网络错误'
			} else if (error.status == 404) {
				message = '请求不存在'
			} else if (error.status == 500) {
				message = '服务错误'
			}
			ElMessage({
				message: message,
				type: 'error',
				grouping: true,
			})
		})
    })
}

export default request